<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目状态更新测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f7fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .test-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .test-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .test-buttons button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary { background: #007bff; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-warning { background: #ffc107; color: #212529; }
        .btn-danger { background: #dc3545; color: white; }
        
        .result {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            border-left: 4px solid #007bff;
            margin-top: 15px;
        }
        
        .result.success {
            border-left-color: #28a745;
            background: #d4edda;
        }
        
        .result.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        
        .result pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .project-list {
            margin-top: 20px;
        }
        
        .project-item {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 10px;
            border-left: 4px solid #007bff;
        }
        
        .project-item h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .project-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .project-detail {
            font-size: 14px;
        }
        
        .project-detail strong {
            color: #666;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-pending { background: #fff3cd; color: #856404; }
        .status-in-progress { background: #d4edda; color: #155724; }
        .status-completed { background: #d1ecf1; color: #0c5460; }
        .status-on-hold { background: #f8d7da; color: #721c24; }
        .status-rejected { background: #f5c6cb; color: #721c24; }
        
        .update-form {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 10px;
        }
        
        .update-form select {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .update-form button {
            padding: 5px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            background: #007bff;
            color: white;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔧 项目状态更新测试</h1>
        <p>测试项目状态修改功能是否正常工作</p>
    </div>

    <!-- 登录区域 -->
    <div class="test-section">
        <h3>🔐 登录</h3>
        <div class="test-buttons">
            <button class="btn-primary" onclick="login()">登录 (sbxnh/123456)</button>
            <button class="btn-success" onclick="checkLoginStatus()">检查登录状态</button>
        </div>
        <div id="loginResult"></div>
    </div>

    <!-- 项目列表和状态更新 -->
    <div class="test-section">
        <h3>📊 项目列表和状态更新</h3>
        <div class="test-buttons">
            <button class="btn-primary" onclick="loadProjects()">加载项目列表</button>
            <button class="btn-warning" onclick="testStatusUpdate()">测试状态更新</button>
            <button class="btn-success" onclick="refreshAndCompare()">刷新并对比</button>
        </div>
        <div id="projectResult"></div>
        <div id="projectList" class="project-list"></div>
    </div>

    <!-- 详细测试日志 -->
    <div class="test-section">
        <h3>📝 测试日志</h3>
        <div id="testLog"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';
        let token = '';
        let projects = [];
        let testLog = [];

        // 添加测试日志
        function addLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            testLog.push({ timestamp, message, type });
            updateLogDisplay();
        }

        // 更新日志显示
        function updateLogDisplay() {
            const logDiv = document.getElementById('testLog');
            logDiv.innerHTML = testLog.map(log => `
                <div class="result ${log.type}">
                    <strong>[${log.timestamp}]</strong> ${log.message}
                </div>
            `).join('');
        }

        // 登录功能
        async function login() {
            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: 'sbxnh', password: '123456' })
                });

                if (response.ok) {
                    const data = await response.json();
                    token = data.token;
                    localStorage.setItem('token', token);
                    document.getElementById('loginResult').innerHTML = 
                        '<div class="result success">✅ 登录成功</div>';
                    addLog('登录成功', 'success');
                } else {
                    document.getElementById('loginResult').innerHTML = 
                        '<div class="result error">❌ 登录失败</div>';
                    addLog('登录失败', 'error');
                }
            } catch (error) {
                document.getElementById('loginResult').innerHTML = 
                    '<div class="result error">❌ 网络错误</div>';
                addLog('登录网络错误: ' + error.message, 'error');
            }
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedToken = localStorage.getItem('token');
            if (savedToken) {
                token = savedToken;
                document.getElementById('loginResult').innerHTML = 
                    '<div class="result success">✅ 已登录</div>';
                addLog('检查登录状态: 已登录', 'success');
            } else {
                document.getElementById('loginResult').innerHTML = 
                    '<div class="result error">❌ 未登录</div>';
                addLog('检查登录状态: 未登录', 'error');
            }
        }

        // 加载项目列表
        async function loadProjects() {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    showResult('❌ 请先登录', 'error');
                    return;
                }
            }

            try {
                const response = await fetch(`${API_BASE}/projects`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    projects = await response.json();
                    showResult(`✅ 成功加载 ${projects.length} 个项目`, 'success');
                    displayProjects();
                    addLog(`加载项目列表成功，共 ${projects.length} 个项目`, 'success');
                } else {
                    showResult(`❌ 加载项目失败: HTTP ${response.status}`, 'error');
                    addLog(`加载项目失败: HTTP ${response.status}`, 'error');
                }
            } catch (error) {
                showResult('❌ 网络错误: ' + error.message, 'error');
                addLog('加载项目网络错误: ' + error.message, 'error');
            }
        }

        // 显示项目列表
        function displayProjects() {
            const projectListDiv = document.getElementById('projectList');
            
            if (projects.length === 0) {
                projectListDiv.innerHTML = '<p>暂无项目</p>';
                return;
            }

            projectListDiv.innerHTML = projects.map(project => `
                <div class="project-item">
                    <h4>${project.projectName || '未命名项目'}</h4>
                    <div class="project-details">
                        <div class="project-detail"><strong>ID:</strong> ${project.id}</div>
                        <div class="project-detail"><strong>代码:</strong> ${project.projectCode || '-'}</div>
                        <div class="project-detail"><strong>负责人:</strong> ${project.principalInvestigatorName || '未分配'}</div>
                        <div class="project-detail">
                            <strong>状态:</strong> 
                            <span class="status-badge ${getStatusClass(project.status)}">
                                ${getStatusText(project.status)}
                            </span>
                        </div>
                    </div>
                    <div class="update-form">
                        <label>更新状态:</label>
                        <select id="status-${project.id}">
                            <option value="PENDING_APPROVAL" ${project.status === 'PENDING_APPROVAL' ? 'selected' : ''}>待审批</option>
                            <option value="IN_PROGRESS" ${project.status === 'IN_PROGRESS' ? 'selected' : ''}>进行中</option>
                            <option value="COMPLETED" ${project.status === 'COMPLETED' ? 'selected' : ''}>已完成</option>
                            <option value="ON_HOLD" ${project.status === 'ON_HOLD' ? 'selected' : ''}>暂停中</option>
                            <option value="REJECTED" ${project.status === 'REJECTED' ? 'selected' : ''}>已拒绝</option>
                        </select>
                        <button onclick="updateProjectStatus(${project.id})">更新状态</button>
                    </div>
                </div>
            `).join('');
        }

        // 更新项目状态
        async function updateProjectStatus(projectId) {
            const newStatus = document.getElementById(`status-${projectId}`).value;
            const project = projects.find(p => p.id === projectId);
            
            if (!project) {
                addLog(`未找到项目 ID: ${projectId}`, 'error');
                return;
            }

            addLog(`开始更新项目 "${project.projectName}" 的状态从 "${project.status}" 到 "${newStatus}"`, 'info');

            try {
                // 获取用户列表以获取负责人ID
                const usersResponse = await fetch(`${API_BASE}/users`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (!usersResponse.ok) {
                    throw new Error('获取用户列表失败');
                }

                const users = await usersResponse.json();
                const piUser = users.find(user => user.fullName === project.principalInvestigatorName);
                
                if (!piUser) {
                    throw new Error('未找到项目负责人');
                }

                // 构建更新数据
                const updateData = {
                    projectName: project.projectName,
                    projectCode: project.projectCode,
                    description: project.description || '',
                    startDate: project.startDate,
                    endDate: project.endDate,
                    status: newStatus,
                    budgetAmount: project.budgetAmount,
                    principalInvestigatorId: piUser.id
                };

                addLog(`发送更新请求: ${JSON.stringify(updateData, null, 2)}`, 'info');

                // 发送更新请求
                const response = await fetch(`${API_BASE}/projects/${projectId}`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updateData)
                });

                if (response.ok) {
                    const updatedProject = await response.json();
                    addLog(`✅ 项目状态更新成功: ${JSON.stringify(updatedProject, null, 2)}`, 'success');
                    
                    // 更新本地项目数据
                    const index = projects.findIndex(p => p.id === projectId);
                    if (index !== -1) {
                        projects[index] = updatedProject;
                        displayProjects();
                    }
                } else {
                    const errorText = await response.text();
                    addLog(`❌ 更新失败: HTTP ${response.status} - ${errorText}`, 'error');
                }
            } catch (error) {
                addLog(`❌ 更新错误: ${error.message}`, 'error');
            }
        }

        // 测试状态更新
        async function testStatusUpdate() {
            if (projects.length === 0) {
                showResult('❌ 请先加载项目列表', 'error');
                return;
            }

            const firstProject = projects[0];
            const currentStatus = firstProject.status;
            const newStatus = currentStatus === 'IN_PROGRESS' ? 'COMPLETED' : 'IN_PROGRESS';
            
            addLog(`自动测试: 将项目 "${firstProject.projectName}" 状态从 "${currentStatus}" 改为 "${newStatus}"`, 'info');
            
            // 设置下拉框值
            document.getElementById(`status-${firstProject.id}`).value = newStatus;
            
            // 执行更新
            await updateProjectStatus(firstProject.id);
        }

        // 刷新并对比
        async function refreshAndCompare() {
            const oldProjects = [...projects];
            await loadProjects();
            
            // 对比变化
            oldProjects.forEach(oldProject => {
                const newProject = projects.find(p => p.id === oldProject.id);
                if (newProject && oldProject.status !== newProject.status) {
                    addLog(`✅ 检测到状态变化: 项目 "${oldProject.projectName}" 从 "${oldProject.status}" 变为 "${newProject.status}"`, 'success');
                }
            });
        }

        // 显示结果
        function showResult(message, type = 'info') {
            const resultDiv = document.getElementById('projectResult');
            const className = type === 'success' ? 'result success' : (type === 'error' ? 'result error' : 'result');
            resultDiv.innerHTML = `<div class="${className}">${message}</div>`;
        }

        // 获取状态样式类
        function getStatusClass(status) {
            const statusMap = {
                'PENDING_APPROVAL': 'status-pending',
                'IN_PROGRESS': 'status-in-progress',
                'COMPLETED': 'status-completed',
                'ON_HOLD': 'status-on-hold',
                'REJECTED': 'status-rejected'
            };
            return statusMap[status] || 'status-pending';
        }

        // 获取状态显示文本
        function getStatusText(status) {
            const statusMap = {
                'PENDING_APPROVAL': '待审批',
                'IN_PROGRESS': '进行中',
                'COMPLETED': '已完成',
                'ON_HOLD': '暂停中',
                'REJECTED': '已拒绝'
            };
            return statusMap[status] || status;
        }

        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
            addLog('页面加载完成', 'info');
        };
    </script>
</body>
</html>
